use crate::utils::constant::get_service_config_path;
use serde::{Deserialize, Serialize};
use std::fs::File;
use std::io::Read;

#[derive(Debug, Serialize, Deserialize, Clone)]
struct BaseService {
    protocol: String,
    host: String,
    port: i32,
    urls: Vec<Url>,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
struct Url {
    name: String,
    url: String,
    method: String,
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub(crate) struct ServiceConfig {
    maview: BaseService,
    center: BaseService,
}

impl ServiceConfig {
    pub fn new() -> ServiceConfig {
        let service_config = get_service_config_path();
        let mut service_file = File::open(service_config).expect("服务配置文件不存在");
        let mut service_content = String::new();
        service_file
            .read_to_string(&mut service_content)
            .expect("读取服务配置文件失败");
        let service_config: ServiceConfig =
            serde_yaml::from_str(&service_content).expect("服务配置文件解析失败");
        service_config
    }

    pub fn get_maview_url(&self, name: &str) -> String {
        for url in self.maview.urls.iter() {
            if url.name == name {
                return format!(
                    "{}://{}:{}{}",
                    self.maview.protocol, self.maview.host, self.maview.port, url.url
                );
            }
        }
        panic!("maview url not found");
    }

    pub fn get_maview_method(&self, name: &str) -> String {
        for url in self.maview.urls.iter() {
            if url.name == name {
                return url.clone().method;
            }
        }
        panic!("maview url not found");
    }

    pub fn get_center_url(&self, name: &str) -> String {
        for url in self.center.urls.iter() {
            if url.name == name {
                return format!(
                    "{}://{}:{}{}",
                    self.center.protocol, self.center.host, self.center.port, url.url
                );
            }
        }
        panic!("center url not found");
    }

    pub fn get_center_method(&self, name: &str) -> String {
        for url in self.center.urls.iter() {
            if url.name == name {
                return url.clone().method;
            }
        }
        panic!("maview url not found");
    }
}

#[test]
fn test_service_config() {
    let service_config = ServiceConfig::new();
    println!("{:?}", service_config.get_maview_url("login"));
}
